<template>
	<div class="add-popup">
		<popup ref="popupRef" title="添加用户" :async="true" width="550px" @confirm="handleSubmit" @close="handleClose">
			<el-form ref="formRef" :model="formData" label-width="84px" :rules="formRules">
				<el-form-item label="账号类型" required prop="login_way">
					<el-radio-group v-model="formData.login_way" @change="changeLoginWay()">
						<el-radio :label="0">电子邮箱</el-radio>
						<el-radio :label="1">手机号</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="国际区号" prop="country_code" v-if="formData.login_way == 1">
					<el-select class="flex-1" filterable v-model="formData.country_code" placeholder="请选择国际区号" clearable>
						<el-option v-for="item in optionsData.regioncode" :label="item.code" :value="item.code" />
					</el-select>
				</el-form-item>
				<el-form-item label="手机号" prop="account" v-if="formData.login_way == 1">
					<el-input v-model="formData.account" type="number" placeholder="请输入手机号" clearable />
				</el-form-item>
				<el-form-item label="电子邮箱" prop="account" v-if="formData.login_way == 0">
					<el-input v-model="formData.account" placeholder="请输入电子邮箱" clearable />
				</el-form-item>
				<el-form-item label="密码" prop="password">
					<el-input v-model="formData.password" placeholder="请输入密码" clearable />
				</el-form-item>
				<el-form-item label="邀请码" prop="invite_code">
					<el-input v-model="formData.invite_code" placeholder="请输入邀请码" clearable />
				</el-form-item>
			</el-form>
		</popup>
	</div>
</template>
<script lang="ts" setup>
	import type { FormInstance } from 'element-plus'
	import { useDictOptions } from '@/hooks/useDictOptions'
	import { apiRegioncodeAll } from '@/api/setting/website'
	import { userAdd } from '@/api/consumer'
	import Popup from '@/components/popup/index.vue'
	const emit = defineEmits(['success', 'close'])
	const formRef = shallowRef<FormInstance>()
	const popupRef = shallowRef<InstanceType<typeof Popup>>()
	const formData = reactive({
		login_way:0,
		country_code: '',
		account: '',
		password: '',
		password_confirm: '',
		invite_code: '',
		channel: 3
	})

	const formRules = {
		country_code: [
			{
				required: true,
				message: '请选择国际区号',
	        trigger: ['blur']
			}
		],
		account: [
			{
				required: true,
				message: '请输入账号',
				trigger: ['blur']
			}
		],
		password: [
			{
				required: true,
				message: '请输入密码',
				trigger: ['blur']
			}
		],
	}

	const { optionsData } = useDictOptions<{
		regioncode : any[]
	}>({
		regioncode: {
			api: apiRegioncodeAll
		}
	})


	const open = () => {
		popupRef.value?.open()
	}
	
	const changeLoginWay = async () => {
		formData.account = ''
	}

	const handleSubmit = async () => {
		await formRef.value?.validate()
		await userAdd(formData)
		popupRef.value?.close()
		emit('success')
	}

	const handleClose = () => {
		emit('close')
	}

	defineExpose({
		open,
	})
</script>